package com.its.us.sk.server.tcp.utils;

import com.its.us.sk.server.ws.config.NettyWsConfig;
import com.its.us.sk.server.ws.push.PushLate;
import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * 接收数据处理工具类
 * @Author: master
 * @Date: 2020/11/28 21:36
 * @Version: 1.0
 */
@Slf4j
public class ReceiveUtil {

    /**
     * 将netty的buffer转换成String
     * @param buffer
     * @return
     */
    public final static String getToString(ByteBuf buffer) {
        StringBuilder data = new StringBuilder();
        String msg = null;
        byte[] b = new byte[buffer.readableBytes()];
        buffer.readBytes(b);

        for (int i = 0; i < b.length; i++) {
            String strData = Integer.toHexString(b[i] & 0xFF);
            if (strData.length() == 1) {
                strData = '0' + strData;
            }
            data.append(strData.toUpperCase());
            msg = data.toString().toUpperCase();
        }
        return msg;
    }

    /**
     * 将消息推送给所有
     * @param msg
     */
    public final static void pushAll(String msg){
        NettyWsConfig.getChannelGroup().forEach(channel -> {
            PushLate.pushCurrent(channel,msg);
        });
    }

    /**
     * 将消息推送给某个用户
     * @param msg
     */
    public final static void pushToOne(String id,String msg){
        if(StringUtils.isNotBlank(id)){
            NettyWsConfig.getUserChannelMap().forEach((s, channel) -> {
                if(id.equals(s)){
                    PushLate.pushCurrent(channel,msg);
                }
            });
        }else{
            log.error("推送web消息：","需要指定用户标识id");
        }
    }
}
